
$(document).ready(function() {
    
    $('#form').submit(function(form){
        
        // Prevent the default click action
        form.preventDefault();
        
        var url = $('form').attr('action');
        
        // Get all the parameters from the URL
        var settingsObj = getUrlParameters(url);
        
        $.ajax({
          url: "?form="+settingsObj.form+"&action="+settingsObj.action+"&"+$('#form').serialize(),
          success: function(response){
             
            var response = jQuery.parseJSON(response);
             
            switch(response.type){
                case 'error':
                    
                    switch(response.errorType) {
                        case 'errorbox':
                            $('#formErrors').html('');
                            $('#formErrors').append('<div class="errorResponse">'+response.message+'</div>');
                            break;
                        case 'alert':
                            alert(response.message);
                            break;
                    }
                        
                        
                    break;
                case 'goto':
                    window.location = response.location;
                    break;
                case 'function':
                    eval(response.functionName);
                    break;
                case 'clear':
                    
                    // We clear all the fields on the form
                    $('.componentField').each(function(index){
                       $(this).val(""); 
                    });
                    
                    if(response.message != '') {
                       alert(response.message);
                    }
                        
                    break;
                case 'closeFormWindow':
                    parent.closeModalWindow();
                    parent.window.location = response.location;
                    break;
            }
            
          }
        });
        
    });
    
});

function getUrlParameters(url) {
  
    var settingsObj = {};
    var attributes = url.split('?');

    if(attributes.length > 0) {
        var parameters = attributes[1].split('&');

        // Place all the parameters in an array
        for(var i in parameters){
            var hash = parameters[i].split('=');
            settingsObj[hash[0]] = hash[1];
        }
    }

    return settingsObj;
  
}